package com.youcan.controller.modelcontroller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.Restrictions;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.youcan.entity.Message;
import com.youcan.entity.User;
import com.youcan.service.modelservices.MessageService;
import com.youcan.service.modelservices.UserService;
import com.youcan.util.Constants;

/**
 * @author time E-mail:timezone85@gmail.com
 * @date:2012-8-19 上午11:07:06
 * @version :V1.0
 *
 */

@Component
@Controller
public class MessageController {
	protected final Log logger = LogFactory.getLog(MessageController.class);

	@Autowired
	@Qualifier("messageServiceImpl")
	private MessageService messageService;
	
	@Autowired
	@Qualifier("userServiceImpl")
	private UserService userService;

	//通过注解进行转发控制 POST来的请求并把参数绑定
	@ResponseBody
	@RequestMapping(value = "/AddMessage", method = RequestMethod.POST)
	public JSONObject AddCollect(
			@RequestParam("userName") String userName,
			@RequestParam("inputDate") Date inputDate,//商家？
			@RequestParam("content") String content,
			@RequestParam("ip") String ip,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, JSONException {
		
		Message message = new Message();
		JSONObject json = new JSONObject();
		try {
			
		    List<User> userList = userService.findByCriteria(Restrictions.eq("userName", userName));
			if(!userList.isEmpty())
			{
				message.setUserId(userList.get(0).getUserId());
		    }
			message.setInputDate(inputDate);
			message.setContent(content);
			message.setIp(ip);
			
			messageService.addEntity(message);
			json.put(Constants.RES_CODE, Constants.CODE_SUCCESS);
			json.put(Constants.RES_MESSAGE, "评论成功。");
		} catch (Exception e) {
			json.put(Constants.RES_CODE, Constants.CODE_FAILED);
			json.put(Constants.RES_MESSAGE, "评论失败。");
		}

		return json;
	}
}
